function setFistTag(list) {
  if (list.length === 1) {
    list[0].close = false;
  } else {
    // list.some(a => {
    //   a.close = true;
    // });
  }
  return list;
}

// 重新设置组件缓存的数组
function setCacheList (state) {
  let _cacheList = [];
  let tagList = state.tagList;
  tagList.map(item => {
    let valArr = item.value.split('/');
    let val = valArr[valArr.length - 1];
    if(val !== 'editCompany') { // 不缓存某些组件 2021-11-1
      _cacheList.push(val);
    }
  });
  state.cacheList = _cacheList;
}

export default {
  state: {
    tagList: [],
    cacheList: [],
    tagIndex: {
      label: "",
      value: "",
      close: false
    },
    tagCurrent: {
      label: '',
      value: '',
      close: ''
    },
    defaultItem: '', // 默认首页为
  },
  mutations: {
    ADD_TAG: (state, action) => {
      state.tagCurrent = action;
      let isHave = state.tagList.some((item) => item.value === action.value);
      if (!isHave) {
        state.tagList.map((item) => {
          item.close = false;
        });
        action.close = true;
        state.tagList = [...state.tagList, action];
      } else {
        state.tagList.map((item) => {
          item.close = false;
          if (item.value === action.value) {
            item.query = action.query;
            item.close = true;
            item.label = action.label;
          }
        });
      }
      setCacheList(state);
    },
    DEL_TAG: (state, action) => {
      state.tagList.forEach((ele, num) => {
        if (ele.value === action.value) {
          state.tagList.splice(num, 1);
          state.tagList = setFistTag(state.tagList);
        }
      });
      setCacheList(state);
    },
    DEL_TAG_OTHER: (state, action) => {
      state.tagList.forEach((ele, num) => {
        if (ele.value === state.tagCurrent.value) {
          state.tagList = state.tagList.slice(num, num + 1);
          state.tagList[0].close = true;
        }
      });
      state.tagList = [...state.tagList];
      setCacheList(state);
    },
    DEL_ALL_TAG: (state, action) => {
      let DeItem = state.defaultItem.request ? state.defaultItem : state.defaultItem.Children[0];
      state.tagCurrent = state.tagIndex = {
        label: DeItem.name,
        value: DeItem.request,
        close: false
      };
      state.tagList = [state.tagIndex];
      setCacheList(state);
    },
    setCacheList: (state, action) => {
      state.cacheList = action;
    },
    setDefault: (state, action) => {
      state.defaultItem = action;
    },
  },
  actions: {
    getCacheList ({ commit }, _cacheList) {
      commit("setCacheList", _cacheList);
    },
    getDefault ({ commit }, defaultItem) {
      commit("setDefault", defaultItem);
    },
  }
};
